package com.example.parkinglotmanagementsystem;

import javafx.collections.FXCollections;

import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

import java.io.FileWriter;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class MainController {
    public static ArrayList<Vehicle> data = new ArrayList<>();
    public static int EditID = -1;

    public MenuItem MenuSaveAsButton;
    public MenuItem MenuExitButton;
    public MenuItem MenuSaveButton;
    public MenuItem MenuOpenFileButton;
    public MenuItem MenuNewFileButton;
    public Button AddVehicleButton;
    public Button SearchButton;
    public Button RefreshButton;
    public Button EditButton;
    public Button DeleteButton;
    public TableView<Vehicle> DataTable;
    public TableColumn TableID;
    public TableColumn TableNumber;
    public TableColumn TableCompany;
    public TableColumn TableTime;
    public TableColumn TableType;
    public TableColumn TableKilo;
    public TableColumn TableConsumption;
    public TableColumn TableExpense;
    public TableColumn TableRoadExpense;
    public TableColumn TableTotalExpense;
    public TableColumn TableLoadWeight;
    public TableColumn TableCarriageNumber;
    public TableColumn TableCargoCapacity;
    public TextField SearchID;
    public TextField SearchNumber;
    public TextField SearchType;
    public TextField EditOrDelID;
    public Label LabelSedanCar;
    public Label LabelTruck;
    public Label LabelBus;


    public void initialize(){
        initializeDataTable();
        initialData();
    }


    public void initializeDataTable(){
        TableID.setCellValueFactory(new PropertyValueFactory<Vehicle,Integer>("id"));
        TableNumber.setCellValueFactory(new PropertyValueFactory<Vehicle,String>("number"));
        TableCompany.setCellValueFactory(new PropertyValueFactory<Vehicle,String>("company"));
        TableTime.setCellValueFactory(new PropertyValueFactory<Vehicle,String>("time"));
        TableType.setCellValueFactory(new PropertyValueFactory<Vehicle,String>("type"));
        TableKilo.setCellValueFactory(new PropertyValueFactory<Vehicle,Float>("totalKilo"));
        TableConsumption.setCellValueFactory(new PropertyValueFactory<Vehicle,Float>("consumption"));
        TableExpense.setCellValueFactory(new PropertyValueFactory<Vehicle,Float>("maintenanceExpense"));
        TableRoadExpense.setCellValueFactory(new PropertyValueFactory<Vehicle,Float>("roadMaintenanceExpense"));
        TableTotalExpense.setCellValueFactory(new PropertyValueFactory<Vehicle,Float>("totalExpense"));
        TableLoadWeight.setCellValueFactory(new PropertyValueFactory<Truck,Float>("loadedWeight"));
        TableCarriageNumber.setCellValueFactory(new PropertyValueFactory<SedanCar,Float>("carriageNumber"));
        TableCargoCapacity.setCellValueFactory(new PropertyValueFactory<Bus,Float>("cargoCapacity"));
    }


    public void initialData(){
        try {
            BufferedReader br = new BufferedReader(new FileReader(System.getProperty("user.home")+"/Desktop/数据库"));

            String line;

            while ((line = br.readLine()) != null) {


                // 按照空格分割每行数据
                String[] data = line.split(" ");
                if(data.length!=13)continue;

                // 假设文件中每行数据的顺序与拼接数据时的顺序一致
                String id = data[0];
                String number = data[1];
                String company = data[2];
                String time = data[3];
                String type = data[4];
                String totalKilo = data[5];
                String consumption = data[6];
                String maintenanceExpense = data[7];
                String roadMaintenanceExpense = data[8];
                String totalExpense = data[9];
                String loadedWeight = data[10];
                String carriageNumber = data[11];
                String cargoCapacity = data[12];

                if(!cargoCapacity.equals("-1")){
                    Bus bus = new Bus(Integer.parseInt(id),number, company, time, type,
                            Float.parseFloat(totalKilo),Float.parseFloat(consumption),
                            Float.parseFloat(maintenanceExpense),Float.parseFloat(roadMaintenanceExpense),
                            Float.parseFloat(totalExpense),Float.parseFloat(cargoCapacity));

                    MainController.data.addAll(FXCollections.observableArrayList(bus));
                }

                if(!carriageNumber.equals("-1")){
                    SedanCar sedanCar = new SedanCar(Integer.parseInt(id),number, company, time, type,
                            Float.parseFloat(totalKilo),Float.parseFloat(consumption),
                            Float.parseFloat(maintenanceExpense),Float.parseFloat(roadMaintenanceExpense),
                            Float.parseFloat(totalExpense),Integer.parseInt(carriageNumber));

                    MainController.data.addAll(FXCollections.observableArrayList(sedanCar));
                }

                if(!loadedWeight.equals("-1")){
                    Truck truck = new Truck(Integer.parseInt(id),number, company, time, type,
                            Float.parseFloat(totalKilo),Float.parseFloat(consumption),
                            Float.parseFloat(maintenanceExpense),Float.parseFloat(roadMaintenanceExpense),
                            Float.parseFloat(totalExpense),Float.parseFloat(loadedWeight));

                    MainController.data.addAll(FXCollections.observableArrayList(truck));
                }
            }

            br.close();
            DataTable.getItems().setAll(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void MenuNewFileAction() {

    }
    public void MenuOpenFileAction() {

    }
    public void MenuSaveAction() throws IOException{
        FileWriter fw = new FileWriter(System.getProperty("user.home")+"/Desktop/数据库",false);
        fw.write("");
        for (Vehicle datum : data) {
            String s = datum.getAllProperty();
            fw.write(s);
        }
        fw.close();
    }

    public void MenuSaveAsAction(){
    }

    public void MenuExitAction() {
        Stage stage = (Stage) SearchButton.getScene().getWindow();
        stage.close();
    }

    public void OnAddAction() throws IOException{
        Stage stage = (Stage) SearchButton.getScene().getWindow();
        Scene addScene = new Scene(new FXMLLoader(Application.class.getResource("Add-View.fxml")).load());
        stage.setScene(addScene);
    }

    public void OnSearchAction() {
        int index = Integer.parseInt(SearchID.getText().isEmpty()?"0":SearchID.getText());
        String number = SearchNumber.getText();
        String type = SearchType.getText();
        ArrayList<Vehicle> SearchedData = new ArrayList<>();
        for (Vehicle datum : data) {
            if(datum.getId()==index || datum.getNumber().equals(number)
               || datum.getType().equals(type))
                SearchedData.add(datum);
        }
        DataTable.getItems().setAll(SearchedData);
    }

    public void OnRefreshAction() {
        DataTable.getItems().setAll(data);
        int sumBus = 0,sumSedanCar = 0,sumTruck = 0;
        for (Vehicle datum : data) {
            if (datum.getType().equals("大巴车"))sumBus++;
            if (datum.getType().equals("小轿车"))sumSedanCar++;
            if (datum.getType().equals("卡车"))sumTruck++;
        }
        LabelBus.setText("大巴车："+sumBus+"辆");
        LabelSedanCar.setText("小轿车："+sumSedanCar+"辆");
        LabelTruck.setText("卡车："+sumTruck+"辆");
    }

    public void OnEditAction() throws IOException{
        EditID = Integer.parseInt(EditOrDelID.getText().isEmpty()?"0":EditOrDelID.getText());
        if(EditID <= data.size() && EditID > 0){
            Stage stage = (Stage) SearchButton.getScene().getWindow();
            stage.setScene(new Scene(new FXMLLoader(Application.class.getResource("Edit-View.fxml")).load()));
        }else System.out.println("找不到编号为" + EditID + "的车辆");
    }

    public void OnDeleteAction() {
        int index = Integer.parseInt(EditOrDelID.getText().isEmpty()?"0":EditOrDelID.getText());
        if(index <= data.size() && index > 0){
            data.remove(index-1);
            for (Vehicle datum : data) {
                datum.setId(data.indexOf(datum)+1);
            }
            DataTable.getItems().setAll(data);
        }else System.out.println("找不到编号为" + index + "的车辆");

    }
}